package com.ruoyi.jiaopei.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.jiaopei.domain.TbClassStudent;
import com.ruoyi.jiaopei.domain.TbKj;
import com.ruoyi.jiaopei.domain.TbSortCurriculum;
import com.ruoyi.jiaopei.service.ITbClassStudentService;
import com.ruoyi.jiaopei.service.ITbCurriculumService;
import com.ruoyi.jiaopei.service.ITbSortCurriculumService;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.ruoyi.jiaopei.domain.bo.TbClassBo;
import com.ruoyi.jiaopei.domain.vo.TbClassVo;
import com.ruoyi.jiaopei.domain.TbClass;
import com.ruoyi.jiaopei.mapper.TbClassMapper;
import com.ruoyi.jiaopei.service.ITbClassService;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 班级Service业务层处理
 *
 * @author macy
 * @date 2024-04-03
 */
@RequiredArgsConstructor
@Service
public class TbClassServiceImpl implements ITbClassService {

    private final TbClassMapper baseMapper;
    private final ITbCurriculumService curriculumService;
    private final ITbClassStudentService classStudentService;

    private final ISysUserService sysUserService;


    @Autowired
    @Lazy
    private  ITbSortCurriculumService sortCurriculumService;







    /**
     * 查询班级
     */
    @Override
    public TbClassVo queryById(Long id){
        TbClassVo vo=baseMapper.selectVoById(id);
        if(null!=vo){
            if(null!=vo.getCurriculumId()){
                vo.setCurriculumVo(curriculumService.queryById(vo.getCurriculumId()));
            }
            if(null!=vo.getCurriculumId()){
                vo.setTeacherVo(sysUserService.selectUserById(vo.getTeacherId()));
            }
        }
        return vo;
    }


    /**
     * 查询班级列表
     */
    @Override
    public TableDataInfo<TbClassVo> queryPageList(TbClassBo bo, PageQuery pageQuery) {
        QueryWrapper<TbClass> lqw = buildQueryWrapper2(bo);
        Page<TbClassVo> result = baseMapper.selectPageList(pageQuery.build(),lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询班级列表
     */
    @Override
    public List<TbClassVo> queryList(TbClassBo bo) {
        LambdaQueryWrapper<TbClass> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TbClass> buildQueryWrapper(TbClassBo bo) {
        return Wrappers.query(TbClass.class)
         .eq(StringUtils.isNotBlank(bo.getName()), "t.name", bo.getName())
         .eq(StringUtils.isNotBlank(bo.getState()), "t.state", bo.getState())
         .eq(bo.getTeacherId() != null, "t.teacher_id", bo.getTeacherId())
         .eq(bo.getCurriculumId() != null, "t.curriculum_id", bo.getCurriculumId())
        .lambda();
    }

    private QueryWrapper<TbClass> buildQueryWrapper2(TbClassBo bo) {
        return Wrappers.query(TbClass.class)
            .like(StringUtils.isNotBlank(bo.getName()), "t.name", bo.getName())
            .eq(StringUtils.isNotBlank(bo.getState()), "t.state", bo.getState())
            .like(StringUtils.isNotBlank(bo.getTeacherName()), "u.nick_name", bo.getTeacherName())
            .eq(bo.getTeacherId() != null, "t.teacher_id", bo.getTeacherId())
            .eq(bo.getCurriculumId() != null, "t.curriculum_id", bo.getCurriculumId())
            ;
    }

    /**
     * 新增班级
     */
    @Override
    public Boolean insertByBo(TbClassBo bo) {
        TbClass add = BeanUtil.toBean(bo, TbClass.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改班级
     */
    @Override
    public Boolean updateByBo(TbClassBo bo) {
        TbClass update = BeanUtil.toBean(bo, TbClass.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TbClass entity){
        if(null==entity.getId()){
            entity.setCreatedDate(new Date());
        }
    }

    /**
     * 批量删除班级
     */
    @Override
    public Boolean deleteWithValidByIds(List<Long> ids, Boolean isValid) {
        if(isValid){
            for (int i = 0; i <ids.size() ; i++) {
                long count=classStudentService.selectCount(new LambdaQueryWrapper<TbClassStudent>()
                    .eq(TbClassStudent::getClassId,ids.get(i))
                );
                if(count>0){
                    throw new ServiceException("班级下还有学员，不能删除。");
                }

                count=sortCurriculumService.selectCount(new LambdaQueryWrapper<TbSortCurriculum>()
                    .eq(TbSortCurriculum::getClassId,ids.get(i))
                );
                if(count>0){
                    throw new ServiceException("班级下还有排课，不能删除。");
                }

            }
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
